<template>
  <div>
    <el-form :inline="true" ref="form" label-width="80px" :model="cForm">
      <el-form-item label="一级分类">
        <el-select
          placeholder="请选择"
          v-model="cForm.category1Id"
          @change="getC2List"
        >
          <el-option
            :label="c1.name"
            :value="c1.id"
            v-for="(c1, index) in c1List"
            :key="c1.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级分类">
        <el-select
          placeholder="请选择"
          v-model="cForm.category2Id"
          @change="getC3List"
        >
          <el-option
            :label="c2.name"
            :value="c2.id"
            v-for="c2 in c2List"
            :key="c2.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="三级分类">
        <el-select placeholder="请选择" v-model="cForm.category3Id" @change='handler'>
          <el-option :label="c3.name" :value="c3.id" v-for="c3 in c3List" :key="c3.id"></el-option>
        </el-select>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
export default {
  name: "Category",
  data() {
    return {
      // 收集数据的地方
      cForm: {
        category1Id: "",
        category2Id: "",
        category3Id: "",
      },
      // 存储一级分类的数据
      c1List: [],
      // 存储二级分类的数据
      c2List: [],
      //   存储三级分类的数据
      c3List: [],
    };
  },
  mounted() {
    this.getC1List();
  },
  methods: {
    // 获取一级分类的数据
    async getC1List() {
      let result = await this.$ajax.attr.reqCategory1();
      if (result.code == 200) {
        this.c1List = result.data;
      }
    },
    // 获取二级分类的数据
    async getC2List() {
        // 每一次数据发生改变的时候清空 二级,三级的数据
        this.c2List=[];
        this.c3List=[];
        this.cForm.category2Id=this.cForm.category3Id=''
      // 携带一级分类的id,获取二级分类的数据
      const { category1Id } = this.cForm;
    //   传给父组件
    this.$emit("getCategoryId",{id:category1Id,flag:1})
      let result = await this.$ajax.attr.reqCategory2(category1Id);
      if (result.code == 200) {
        this.c2List = result.data;
      }
    },
    // 获取三级分类的数据
    async getC3List() {
        // 清空三级分类的数据+id
        this.c3List=[];
        this.cForm.category3Id='';
      // 携带二级分类的id,获取三级分类的数据
      const { category2Id } = this.cForm;
    this.$emit("getCategoryId",{id:category2Id,flag:2})

      let result = await this.$ajax.attr.reqCategory3(category2Id);
      if (result.code == 200) {
        this.c3List = result.data;
      }
    },

    handler(){
        const { category3Id }=this.cForm;
        // 给父组件传递过去
        this.$emit("getCategoryId",{id:category3Id,flag:3})
    }
  },
};
</script>

<style>
</style>